package org.example.admin.controller;

import org.example.admin.exception.ControllerException;
import org.example.admin.utils.StringUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping("/tinymce")
public class TinymceController {

    @Value("${avatarImageLocation}")
    private String imageLocation;

    @Value("${imageServer}")
    private String imageServer;


    @RequestMapping("/upload")
    public Object upload(MultipartFile file){
        // 获取文件的原始名字
        String originFileName = file.getOriginalFilename();

        // 获取文件的后缀： .png .jpg XXXX
        String fileSuffix = originFileName.substring(originFileName.lastIndexOf("."));

        // 新的文件名
        String newFileName = System.nanoTime() + StringUtils.generateRandomString(10) + fileSuffix;

        try {
            file.transferTo(new File(imageLocation + newFileName));  // D:/nginx-server/images/8877776656afeji786766.png
        } catch (IOException ioException) {
            throw new ControllerException(ioException.getMessage());
        }        Map<String,String> map =new HashMap<>();

        map.put("location",imageServer+newFileName);
        return map;
    }
}
